package es.ull.opendata.px2scovo.pcaxis.fileparser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;

//TODO: (PFC) Realizar documentación definitiva.
/*(Documentación provisional) 
 * This class extends the class java.io.BufferedReader. This class overrides
 * readLine method in order to change the concept of line.
 * 
 * In this class, a line ends with a semicolon, or semicolon followed by
 * carriage return ('\r') or line feed ('\n').
 * 
 * @author Sergio Gonz&aacute;lez Cruz
 * @author Israel Beltr&aacute;n Valent&iacute;n
 * @version 0.1
 * @since JDK1.6
 */
public class PXReader extends BufferedReader {

	private final static String lineSeparator = ";";
	private final static String endLineRegExp = lineSeparator + " *$";

	/**
	 * Constructor passing reader and buffer size.
	 * 
	 * @param in
	 *           a reader.
	 * @param sz
	 *           buffer size.
	 * @see <a
	 *      href="http://download.oracle.com/javase/6/docs/api/java/io/BufferedReader.html#BufferedReader(java.io.Reader,%20int)">Java.io.BufferedReader</a>
	 */
	public PXReader(Reader in, int sz) {
		super(in, sz);
	}

	/**
	 * Constructor passing reader and buffer size.
	 * 
	 * @param in
	 *           a reader
	 * @see <a
	 *      href="http://download.oracle.com/javase/6/docs/api/java/io/BufferedReader.html#BufferedReader(java.io.Reader)"></a>
	 */
	public PXReader(Reader in) {
		super(in);
	}

	/**
	 * This method read a line that ends with semicolon or semicolon followed by
	 * carriage return ('\r') or line feed ('\n').
	 * 
	 * @return A String with the contents of the line, including the semicolon,
	 *         but not any line-terminator characters. Also returns null when the
	 *         end of the stream has been reached, or it is a empty file; also if
	 *         reaches the end of the stream without find any "line".
	 * @throws IOException
	 *            if an I/O error occurs.
	 */
	@Override
	public String readLine() throws IOException {

		String line = "";
		
		do {
			String currentLine = super.readLine();

			if (currentLine == null) {
				return null;
			} else {
				currentLine = new String(currentLine.replaceAll(endLineRegExp, lineSeparator));
				
				if (currentLine.endsWith(lineSeparator)) {
					return replaceDoubleQuotes(line + currentLine.substring(0, currentLine.length() - 1));
				} else {
					line += currentLine;
				}
			}
		} while (true);
	}

	/**
	 * It's for multilines cases.
	 * 
	 * @param line
	 * @return line without double quotes
	 */
	private String replaceDoubleQuotes(String line) {
		return line.replaceAll("\"\"", "");
	}

}
